package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNResponse;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNGetUserResponse;
import com.github.postsanf.yinian.utils.BigDecimalUtil;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.google.gson.Gson;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

import cn.beecloud.BCPay;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

public class MyHongbaoPayDialogActivity extends Activity implements View.OnClickListener {
    private RelativeLayout rl_mywallet;
    private RelativeLayout dialog_mywallet;
    private TextView tv_mymoney;
    private ImageView hongbao_pay_sanjiao;
    private LinearLayout zhifu1, zhifu2;
    private ImageView hongbao_pay_yuer1, hongbao_pay_zhifubao1, hongbao_pay_yuer2, hongbao_pay_zhifubao2;
    private BaseApplication application;
    private String totalPrice;
    private String totalgeshu;
    private String uBalance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_dialog_hongbaopay);
        application = (BaseApplication) getApplication();
        totalPrice = getIntent().getStringExtra("totalPrice");
        totalgeshu = getIntent().getStringExtra("totalgeshu");
        initView();
        getUserWallet();
    }

    private void getUserWallet() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNGetUserResponse resUser = new Gson().fromJson(s, YNGetUserResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            uBalance = resUser.getData().get(0).getuBalance();
                            if (!StringUtils.isEmpty(uBalance)) {
                                if (BigDecimalUtil.multotal(uBalance, "100") > BigDecimalUtil.multotal(totalPrice, "100")) {
                                    hongbao_pay_sanjiao.setVisibility(View.GONE);
                                } else {
                                    hongbao_pay_sanjiao.setVisibility(View.VISIBLE);
                                }

                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }

    private void initView() {
        findViewById(R.id.mywallet_close).setOnClickListener(this);
        findViewById(R.id.hongbao_pay_sanjiao).setOnClickListener(this);
        tv_mymoney = (TextView) findViewById(R.id.tv_mymoney);
        tv_mymoney.setText(totalPrice);
        hongbao_pay_sanjiao = (ImageView) findViewById(R.id.hongbao_pay_sanjiao);
        zhifu1 = (LinearLayout) findViewById(R.id.zhifu1);
        hongbao_pay_yuer1 = (ImageView) findViewById(R.id.hongbao_pay_yuer1);
        hongbao_pay_zhifubao1 = (ImageView) findViewById(R.id.hongbao_pay_zhifubao1);
        hongbao_pay_yuer1.setOnClickListener(this);
        hongbao_pay_zhifubao1.setOnClickListener(this);
        zhifu2 = (LinearLayout) findViewById(R.id.zhifu2);
        hongbao_pay_yuer2 = (ImageView) findViewById(R.id.hongbao_pay_yuer2);
        hongbao_pay_zhifubao2 = (ImageView) findViewById(R.id.hongbao_pay_zhifubao2);
        hongbao_pay_yuer2.setOnClickListener(this);
        hongbao_pay_zhifubao2.setOnClickListener(this);
        dialog_mywallet = (RelativeLayout) findViewById(R.id.dialog_mywallet);
        dialog_mywallet.setOnClickListener(this);
        rl_mywallet = (RelativeLayout) findViewById(R.id.rl_mywallet);
        rl_mywallet.setOnClickListener(this);
        Animation translateAnimationf = new TranslateAnimation(0, 0, -UIHelper.dip2px(MyHongbaoPayDialogActivity.this, 220), 0);
        translateAnimationf.setDuration(500);
        rl_mywallet.startAnimation(translateAnimationf);
        findViewById(R.id.mywallet_getcash).setOnClickListener(this);
    }

    boolean isZhifubao = false;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.hongbao_pay_sanjiao:
                zhifu1.setVisibility(View.VISIBLE);
                break;
            case R.id.hongbao_pay_zhifubao1:
                zhifu1.setVisibility(View.GONE);
                zhifu2.setVisibility(View.VISIBLE);
                isZhifubao = true;
                break;
            case R.id.hongbao_pay_yuer2:
                zhifu2.setVisibility(View.GONE);
                zhifu1.setVisibility(View.VISIBLE);
                isZhifubao = false;
                break;
            case R.id.mywallet_close:
            case R.id.dialog_mywallet:
                dialog_mywallet.setClickable(false);
                Animation translateAnimationf = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(MyHongbaoPayDialogActivity.this, 600));
                translateAnimationf.setDuration(600);
                rl_mywallet.startAnimation(translateAnimationf);
                translateAnimationf.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        rl_mywallet.setVisibility(View.GONE);
                        finish();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                break;
            case R.id.rl_mywallet:
                break;
            case R.id.mywallet_getcash:
                if (!isZhifubao) {
                    PayYueEe();
                } else {
                    DownOrder(totalPrice);
                }
                break;
        }
    }

    public void PayYueEe() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNGetUserResponse resUser = new Gson().fromJson(s, YNGetUserResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            String yueer = resUser.getData().get(0).getuBalance();
                            Log.i("xjs", "yueer==>" + yueer);
                            if (!StringUtils.isEmpty(yueer)) {
                                if (BigDecimalUtil.multotal(yueer, "100") < BigDecimalUtil.multotal(totalPrice, "100")) {
                                    Toast.makeText(MyHongbaoPayDialogActivity.this, "余额不足", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                Intent intent = new Intent("updateMoney");
                                intent.putExtra("totalPrice", totalPrice);
                                intent.putExtra("totalgeshu", totalgeshu);
                                sendBroadcast(intent);
                                sendBroadcast(new Intent(ACTIONs.actionCloseactivity));
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }

    String orderNumber;

    public void DownOrder(final String topayPrice) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("money", topayPrice);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/PlaceOrder")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "zsss==>" + s.toString());
                        try {
                            JSONObject resultOrder = new JSONObject(s.toString());
                            if (ReqUtils.isSuccess(resultOrder.optString("code"))) {
                                String transactionID = resultOrder.optJSONArray("data").optJSONObject(0).optString("transactionID");
                                orderNumber = resultOrder.optJSONArray("data").optJSONObject(0).optString("orderNumber");
                                HashMap<String, String> mapOptional = new HashMap<>();
                                mapOptional.put("userid", String.valueOf(application.getCurID()));
                                mapOptional.put("transactionID", transactionID);
                                mapOptional.put("orderNumber", orderNumber);
                                Log.i("xjs", "application.getCurID()=>" + application.getCurID());
                                Log.i("xjs", "totalPrice==>" + topayPrice);
                                int zongPrice = BigDecimalUtil.multotal(topayPrice, "100");
                                Log.i("xjs", "zongPrice==>" + zongPrice);
                                if (zongPrice <= 0) {
                                    Toast.makeText(MyHongbaoPayDialogActivity.this, "有误，处理中！", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                BCPay.getInstance(MyHongbaoPayDialogActivity.this).reqAliPaymentAsync("武汉市追忆那年网络科技有限公司", zongPrice,
                                        orderNumber, mapOptional, callback);
                            } else {
                                Toast.makeText(MyHongbaoPayDialogActivity.this, "异常！", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }


    private String toastMsg;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(MyHongbaoPayDialogActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(MyHongbaoPayDialogActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
                    TopUp();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void TopUp() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put("money", totalPrice);
        mParam.put("orderNumber", orderNumber);
        Log.i("xjs", "TopUp==+orderNumber=>" + orderNumber);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/TopUp")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNResponse resUser = new Gson().fromJson(s, YNResponse.class);
                        Log.i("xjs", "TopUp===>" + s);
                        if (resUser != null && resUser.getCode() == 0) {
                            Intent intent = new Intent("updateMoney");
                            intent.putExtra("totalPrice", totalPrice);
                            intent.putExtra("totalgeshu", totalgeshu);
                            sendBroadcast(intent);
                            sendBroadcast(new Intent(ACTIONs.actionCloseactivity));
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }

    BCCallback callback = new BCCallback() {
        @Override
        public void done(BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            String result = bcPayResult.getResult();
            Log.d("yuhao", "result=" + "支付失败, 原因: " + bcPayResult.getErrCode() +
                    " # " + bcPayResult.getErrMsg() +
                    " # " + bcPayResult.getDetailInfo());
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                handler.sendEmptyMessage(2);
            } else if (result.equals(BCPayResult.RESULT_CANCEL)) {
                toastMsg = "用户取消支付";
                handler.sendEmptyMessage(1);
            } else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();
                handler.sendEmptyMessage(1);
            }
            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w("xjs", "bill id retrieved : " + bcPayResult.getId());
                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                // getBillInfoByID(bcPayResult.getId());
            }
        }
    };

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

}
